package mp1.aop.aspect;


import mp1.aop.calculate.Calculator;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class StopWatchAspect {
    final Map<String,Long> metrics= Collections.synchronizedMap(new HashMap<>());

    @Around("execution(public * mp1.service.*.*(..))")
    public void calculateTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long t1= Calendar.getInstance().getTimeInMillis();
        joinPoint.proceed();
        long t2= Calendar.getInstance().getTimeInMillis();
        String methodSig=joinPoint.getSignature().toString();
        long base= metrics.containsKey(methodSig)?metrics.get(methodSig):0;
        long time=base+t2-t1;
        if(time>Calculator.apiCalculator.getMax_time()){
            Calculator.apiCalculator.setMax_time(time);
        }
        if(time<Calculator.apiCalculator.getMin_time()){
            Calculator.apiCalculator.setMin_time(time);
        }
        Calculator.apiCalculator.setAve_time((Calculator.apiCalculator.getAve_time()*(Calculator.apiCalculator.getNumOfUsage()-Calculator.apiCalculator.getNum_of_exception()-1)+time)/Calculator.apiCalculator.getNumOfUsage());
        metrics.put(methodSig,time);
    }

    public Map<String, Long> getMetrics() {
        return metrics;
    }


}
